import React, { useState, useCallback, useEffect } from "react";
import { Select, Badge, Tag, Divider, Popconfirm, message, Spin } from "antd";
import { NextPage } from "next";
import Link from "next/link";
import { Modal } from "antd";
import dayjs from "dayjs";

import { AdminLayout } from "@/layout";
import { SPTDataTable } from "@/components/SPTDataTable";
import style from "./index.module.scss";
import { ArticleApi } from "@/api/article";
import { CategoryApi } from "@/api/categroy";
import { ViewApi } from "@/api/view";
import { ViewChart } from "@/components/ViewChart";
import { useSettings } from "@/hooks/settings";

interface IArticleProps {
  articles: IArticle[];
  total: number;
}
const Article: NextPage<IArticleProps> = ({
  articles: defaultArticles = [],
  total: defaultTotal = 0,
}) => {
  const setting = useSettings();
  // 全部分类
  const [categorys, setCategorys] = useState<ICategory[]>([]);
  // 全部文章
  const [articles, setArticles] = useState(defaultArticles || []);
  // 搜索参数
  const [params, setParams] = useState();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [views, setViews] = useState(null);

  // 表列
  const column = [
    {
      title: "标题",
      key: "title",
      dataIndex: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        return status === "draft" ? (
          <Badge status="warning" text="草稿" />
        ) : (
          <Badge status="success" text="已发布" />
        );
      },
    },
    {
      title: "分类",
      dataIndex: "category",
      key: "category",
      render: (category) =>
        category ? <Tag color="purple">{category.label}</Tag> : null,
    },
    {
      title: "标签",
      dataIndex: "tags",
      key: "tags",
      render: (tags) => (
        <span>
          {tags.map((t) => (
            <Tag key={t.label}>{t.label}</Tag>
          ))}
        </span>
      ),
    },
    {
      title: "阅读量",
      dataIndex: "views",
      key: "views",
      render: (views) => (
        <Badge
          overflowCount={Infinity}
          count={views}
          showZero={true}
          style={{ backgroundColor: "#52c41a" }}
        />
      ),
    },
    {
      title: "发布时间",
      dataIndex: "publishAt",
      key: "publishAt",
      render: (date) => dayjs(date).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (id) => (
        <span style={{ width: 250 }}>
          <Link href={`/article/editor/${id}`}>
            <a target="_blank">编辑</a>
          </Link>
          <Divider type="vertical" />
          <span>
            <a
              onClick={() => {
                setLoading(true);
                ViewApi.getViewsByUrl(
                  `${setting.systemUrl}/article/${id}`
                ).then((res) => {
                  setViews(res);
                  setVisible(true);
                  setLoading(false);
                });
              }}
            >
              查看访问
            </a>
          </span>
          <Divider type="vertical" />
          <Popconfirm
            onConfirm={() => {
              deleteArticle(id);
            }}
            title={"删除文章"}
            okText={"确认"}
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </span>
      ),
    },
  ];

  // 获取文章
  const getArticles = useCallback((params) => {
    return ArticleApi.getArticles(params).then((res) => {
      setArticles(res[0]);
      setParams(params);
      return res;
    });
  }, []);
  // 删除文章
  const deleteArticle = (id) => {
    ArticleApi.deleteArticle(id).then((res) => {
      message.success("删除成功");
      getArticles(params); // 设置Params的意义
    });
  };

  // 初始化数据,需要得到所有分类
  useEffect(() => {
    CategoryApi.getAll().then((res) => {
      setCategorys(res);
    });
  }, []);

  return (
    <AdminLayout>
      <div className={style.wrapper}>
        <SPTDataTable
          columns={column}
          onSearch={getArticles}
          defaultTotal={0}
          data={articles}
          // 搜索项
          searchFields={[
            {
              label: "标题",
              field: "title",
              msg: "请输入标题",
            },
            {
              label: "状态",
              field: "status",
              msg: "选择状态",
              children: (
                <Select style={{ width: 180 }}>
                  {[
                    { label: "已发布", value: "publish" },
                    { label: "草稿", value: "draft" },
                  ].map((s) => (
                    <Select.Option key={s.label} value={s.value}>
                      {s.label}
                    </Select.Option>
                  ))}
                </Select>
              ),
            },
            {
              label: "分类",
              field: "category",
              msg: "选择分类",
              children: (
                <Select style={{ width: 180 }}>
                  {categorys.map((c) => (
                    <Select.Option key={c.id} value={c.id}>
                      {c.label}
                    </Select.Option>
                  ))}
                </Select>
              ),
            },
          ]}
        />
      </div>
      <Modal
        title="访问统计"
        visible={visible}
        footer={false}
        closable={true}
        onCancel={() => {
          setViews([]);
          setVisible(false);
        }}
      >
        {loading ? (
          <Spin spinning={loading}></Spin>
        ) : (
          <ViewChart data={views} />
        )}
      </Modal>
    </AdminLayout>
  );
};
Article.getInitialProps = async () => {
  const res = await ArticleApi.getArticles({ page: 1, pageSize: 12 });
  return { articles: res[0], total: res[1] };
};
export default Article;
